package com.dtkavin.threads;


import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by john on 10/3/16.
 */
public class ReentrantLockDemo {
    public static void main(String[] args) {
        final ShareData shareData = new ShareData();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    shareData.print();
                }
            }).start();
        }
    }

    static class ShareData {
        Lock lock = new ReentrantLock();

        public void print() {
            try {
                lock.lock();
                Thread.sleep(new Random().nextInt(1000));
                System.out.println("print: " + Thread.currentThread().getName());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
